package com.carpedil.shirodemo.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carpedil.shirodemo.system.mapper.RoleMapper;
import com.carpedil.shirodemo.system.mapper.RoleMenuMapper;
import com.carpedil.shirodemo.system.mapper.RoleOperatorMapper;
import com.carpedil.shirodemo.system.model.Role;
import com.carpedil.shirodemo.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 服务实现类
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

  @Autowired private RoleMapper roleMapper;

  @Autowired private RoleMenuMapper roleMenuMapper;
  @Autowired private RoleOperatorMapper roleOperatorMapper;

  @Override
  public Page<Role> selectAllByQuery(Integer page, Integer limit, Role roleQuery) {
    QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
    if (roleQuery != null) {
      queryWrapper.like(
          roleQuery.getRoleName() != null && !roleQuery.equals(""),
          "role_name",
          roleQuery.getRoleName());
    }
    Page<Role> pages = new Page<>((page - 1), limit);
    Page<Role> rolePage = roleMapper.selectPage(pages, queryWrapper);
    return rolePage;
  }

  @Override
  public Integer[] getMenusByRoleId(Integer roleId) {
    return roleMenuMapper.getMenusByRoleId(roleId);
  }

  @Override
  public List<Role> selectAll() {
    return roleMapper.selectList(null);
  }

  @Override
  public Integer[] getOperatorsByRoleId(Integer roleId) {
    return roleOperatorMapper.getOperatorsByRoleId(roleId);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void grantOperator(Integer roleId, Integer[] operatorIds) {
    roleOperatorMapper.deleteByRoleId(roleId);
    if (operatorIds != null && operatorIds.length != 0) {
      for (int i = 0; i < operatorIds.length; i++) {
        operatorIds[i] = operatorIds[i] - 10000;
      }
      roleOperatorMapper.insertRoleOperators(roleId, operatorIds);
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void grantMenu(Integer roleId, Integer[] menuIds) {
    roleOperatorMapper.deleteByRoleId(roleId);
    roleMenuMapper.deleteByRoleId(roleId);
    if (menuIds != null && menuIds.length != 0) {
      roleMenuMapper.insertRoleMenus(roleId, menuIds);
    }
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteRoleById(Integer id) {
    int i = roleMapper.deleteById(id);
    if (i > 0) {
      roleMenuMapper.deleteByRoleId(id);
      roleOperatorMapper.deleteByRoleId(id);
    }
  }
}
